class util {

	constructor(_extends) {
		this.config = _extends.config
	}

	//判断是否json
	isJson(val) {
		return new Promise((resolve, reject) => {
			try {
				try {
					let jsonData = JSON.parse(val)
					resolve(jsonData)
				}
				catch(err){
					resolve(false)
				}
			}
			catch(err) {
				reject(err)
			}
		})
	}

	uuid() {
		const uuid = require('uuid/v1')
		return uuid()
	}

	//执行shell命令
	execShell(command) {
		return new Promise((resolve, reject) => {
			try {
				const childProcess = require('child_process');
				//开启子线程执行命令并返回结果
				childProcess.exec(command, function(err, stdOut, stdErr) {
					if(err || stdErr) {
						console.error(err, stdErr)
						//执行出现错误
						reject([err, stdErr])
					}
					else {
						//执行完毕并返回输出内容
						resolve(stdOut)
					}
				});
				
			}
			catch(err) {
				console.error(err)
				reject(err)
			}
		})
	}
	
	//创建随机字符串
	createRandomStr(len) {
		return new Promise( async (resolve, reject) => {
			let randomStr = ''
			try {
				randomStr = await this.execShell(`head -n 80 /dev/urandom | tr -dc A-Za-z0-9 | head -c ${len}`)
				resolve(randomStr)
			}
			catch(err) {
				console.error('非linux系统无法使用此生成指令，将用传统方法生成', err)
				try {
					randomStr = ''
					let material = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
					for(let i = 0;i < len;i++) {
						//添加在素材字符串随机找到的字符
						randomStr += material[parseInt(Math.random() * 61)];
					}
					await resolve(randomStr)
				}
				catch(err) {
					console.error('生成随机字符串失败', err)
					reject(err)
				}
			}
		})
	}
}

module.exports = util